package com.wenx.v3auth.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 首页控制器
 */
@Slf4j
@Controller
public class HomeController {

    /**
     * 首页
     */
    @GetMapping("/")
    @Operation(
            summary = "访问首页",
            description = "显示系统首页，包含用户信息和权限状态"
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功返回首页视图"),
            @ApiResponse(responseCode = "302", description = "重定向到登录页面")
    })
    public String home(
            @Parameter(hidden = true) Model model
    ) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            model.addAttribute("username", authentication.getName());
            model.addAttribute("authorities", authentication.getAuthorities());

            // 添加用户角色信息用于权限判断
            boolean isAdmin = authentication.getAuthorities().stream()
                    .anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"));
            model.addAttribute("isAdmin", isAdmin);
        }
        log.debug("显示首页，用户: {}", authentication != null ? authentication.getName() : "匿名");
        return "home";
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    @Operation(
            summary = "显示登录页面",
            description = "显示用户登录页面，支持错误信息和登出信息的显示"
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功返回登录页面视图"),
            @ApiResponse(responseCode = "302", description = "已登录用户重定向到首页")
    })
    public String login(
            @Parameter(hidden = true) Model model,
            @Parameter(
                    name = "error",
                    description = "登录错误标识，当登录失败时会传递此参数",
                    required = false
            )
            @RequestParam(value = "error", required = false) String error,
            @Parameter(
                    name = "logout",
                    description = "登出成功标识，当用户成功登出时会传递此参数",
                    required = false
            )
            @RequestParam(value = "logout", required = false) String logout
    ) {

        if (error != null) {
            model.addAttribute("errorMsg", "用户名或密码错误！");
        }

        if (logout != null) {
            model.addAttribute("logoutMsg", "您已成功退出！");
        }

        log.debug("显示登录页面");
        return "login";
    }
} 